/* eslint-disable no-unused-vars */
import clone from "clone";
import { StoreImp } from "./abstract";
import { FormModel } from "./formModel";
import { RuleCheck } from "./ruleCheck";
import { Event } from "./event";
import { DialogController } from "./dialogController";
import { DataSource } from "./dataSource";
import { Component } from "./component";
import { Style } from "./style";
import { LifeCycle } from "./lifeCycle";
import { VirtualDom } from "./vDom";
import { descriptor } from './descriptor'
import { Controller } from './controller'

import { tools } from "./tools";

let store;
let ruleCheck; //表单正则校验

class Store extends StoreImp {

  static defineContainer = [
    "list",
    "columns",
    "container",
    "hiddenColumns",
    "handles",
  ];
  formId; //主表单表名
  tableConfig; //系统默认字段
  className; //实例名称 需要校验只能英文
  query; //链接头参数
  params; //组件外侧传参
  paramsDefine; //外部参数定义
  current; //当前选中组件
  root; //组件树
  componentsMap; //组件Map
  models; //数据提取模型
  modelTree; //
  beginEvents; //应用创建后执行事件集合
  eventMap; //事件Map
  eventCollection; //事件集合
  formDataSource; //表单数据源
  eventCenter;
  style;
  cssText;
  lifeCycle; // 生命周期钩子
  virtualDom;
  designModel; //当前模式 //front-desk background
  configuration; //全局配置信息
  submitInterceptor; //提交拦截器
  controller; // 公共API挂载点
  constructor({
    formId,
    tableConfig,
    params,
    paramsDefine,
    className = "low-code-wrap",
    current = {},
    root = null,
    componentsMap = {},
    models = null,
    cssText = `.low-code-wrap{
      
}    
`,
    beginEvents = [],
    eventMap = {
      SDFAJDLQ: `({form,triggerSource,axios})=>{
  console.log(form) //数据代理
  console.log(triggerSource)  //触发事件组件
  axios({ method: 'get', url: 'http://www.tianqiapi.com/api?version=v1&appid=23035354&appsecret=8YvlPNrz', params:{} }).then((res)=>{
      console.log('res',res)
  })
}`,
    },
    eventCollection = [
      {
        value: "SDFAJDLQ",
        label: "内置事件",
      },
    ],
    formDataSource = {},
    configuration = {
      toView: false, //true 表单查看不可编辑
    },
    submitInterceptor= `(form)=>{
      form.cc=123
      return form
}`
  }) {
    super();
    this.formId = formId || tools.random(5);
    this.tableConfig = tableConfig || {
      creator: true, //创建人
      create_time: true, //创建时间
      updater: true, //更新人
      update_time: true, //更新时间
      deleted: true, //删除
      disabled: true, //禁用
      status: true, //状态
      ver: true, //版本号+
    };
    this.params = params || {};
    this.paramsDefine = paramsDefine || [];
    this.className = className;
    this.current = current;
    this.root = root;
    this.componentsMap = componentsMap;
    this.models = models || {
      aa: null,
      bb: null,
      cc: {
        dd: null,
      },
    };  //默认
    this.beginEvents = beginEvents;
    this.eventMap = eventMap;
    this.eventCollection = eventCollection;
    this.formDataSource = formDataSource;
    this.cssText = cssText;
    this.configuration = configuration;
    this.submitInterceptor=submitInterceptor

    this.query = tools.transformURL(window.location.href);
    ruleCheck = new RuleCheck(this);
    this.controller = new Controller(this);
    this.dataSource = new DataSource(this);
    this.formModel = new FormModel(this);
    this.dialogController = new DialogController(this);
    this.eventCenter = new Event(this);
    this.style = new Style(this);
    this.lifeCycle = new LifeCycle(this);
    this.virtualDom = new VirtualDom(this);

    
    this.designModel = "front-desk";

    this.initParams();
    this.formModel.buildModelsList()
    this.initComponentTree();

    this.style.addNewStyle(this.cssText);
    
    this.lifeCycle.created();
  }
  @descriptor.errorLog()
  initParams() {
    let params = {}
    this.paramsDefine.map(param => {
      params[param.field] = this.params[param.field] || ''
    })
    Object.assign(this.params, params)
  }
  initComponentTree() {
    console.log('initComponentTree')
    this.componentsMap = {};
    let Clist = [];
    this.root.list &&
      this.root.list.length > 0 &&
      this.switchComponent(this.root.list, Clist);
    this.root.list = Clist;

    let CblackList = [];
    this.root.blackList &&
      this.root.blackList.length > 0 &&
      this.switchComponent(this.root.blackList, CblackList);
    this.root.blackList = CblackList;
  }
  findContainers(item) {
    let containers = Object.keys(item).filter(function (v) {
      return Store.defineContainer.indexOf(v) > -1;
    });
    return containers;
  }
  switchComponent(list, Clist) {
    let _this = this;
    list.map((item, index) => {
      let containers = this.findContainers(item);
      // if (item.model) {
      //   Clist.push(new Component(clone(item), _this));
      //   this.componentsMap[Clist[index]["key"]] = Clist[index];
      // } else {
      //   Clist.push(clone(item));
      // }
      let component = new Component(clone(item), _this)
      this.addComponentMap(component)
      Clist.push(component);
      containers.map((containerName) => {
        this.switchComponent(
          item[containerName],
          (Clist[index][containerName] = [])
        );
      });
    });
  }
  generateComponent(obj) {
    let component = new Component(obj, this);
    this.addComponentMap(component);
    return component;
  }
  addComponentMap(node) {
    node.key ? (this.componentsMap[node.key] = node) : null;
  }
  deepCloneComponentMap(list, Clist) {
    let _this = this;
    list.map((item, index) => {
      let containers = this.findContainers(item);
      /**克隆必须生成唯一key */
      let component = new Component(clone(item), _this,true)
      this.addComponentMap(component)
      Clist.push(component);
      containers.map((containerName) => {
        this.deepCloneComponentMap(
          item[containerName],
          (Clist[index][containerName] = [])
        );
      });
    });
  }
  delComponentMap(node) {
    let childNodes =
      node.list ||
      node.columns ||
      node.container ||
      node.hiddenColumns ||
      node.handles;
    childNodes &&
      childNodes.forEach((child) => {
        this.delComponentMap(child);
      });
    delete this.componentsMap[node.key];
  }
  isRepeat(arr) {
    var hash = {};
    for (var i in arr) {
      if (hash[arr[i]]) {
        return true;
      }
      // 不存在该元素，则赋值为true，可以赋任意值，相应的修改if判断条件即可
      hash[arr[i]] = true;
    }
    return false;
  }
  checkRepeat(keyName) {
    return (
      Object.entries(this.componentsMap).filter((item) => {
        return item[1].model == keyName;
      }).length > 1
    );
  }
  openDialog(dialogKey, triggerSourceKey, data) {
    this.dialogController.openDialog(dialogKey, triggerSourceKey, data);
  }
  saveDialog(triggerSourceKey, data) {
    this.dialogController.saveDialog(triggerSourceKey, data);
  }
  selector(model) {
    return this.virtualDom.selector(model);
  }
}

function createStore(arg) {
  store = new Store({ ...arg });
  return store;
}

export { store, ruleCheck, Store, Component, createStore };
